package org.dromara.wmscloud.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.http.HtmlUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.wmscloud.domain.bo.BaseMatBo;
import org.dromara.wmscloud.domain.vo.BaseMatImportVo;
import org.dromara.wmscloud.domain.vo.BaseMatVo;
import org.dromara.wmscloud.service.IBaseMatService;

import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class BaseMatImportListener extends AnalysisEventListener<BaseMatImportVo> implements ExcelListener<BaseMatImportVo> {

    private final IBaseMatService baseMatService;

    private final Boolean isUpdateSupport;

    private final Long operUserId;
    private final Long userDeptId;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public BaseMatImportListener(Boolean isUpdateSupport) {
        this.baseMatService = SpringUtils.getBean(IBaseMatService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operUserId = LoginHelper.getUserId();
        this.userDeptId = LoginHelper.getDeptId();
    }

    @Override
    public void invoke(BaseMatImportVo baseMatImportVo, AnalysisContext context) {
        BaseMatVo baseMatVo = this.baseMatService.selectMatByMatCode(baseMatImportVo.getMatCode());
        try {
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(baseMatVo)) {
                BaseMatBo baseMatBo = BeanUtil.toBean(baseMatImportVo, BaseMatBo.class);
                ValidatorUtils.validate(baseMatBo);
                baseMatBo.setCreateBy(operUserId);
                baseMatBo.setCreateDept(userDeptId);
                baseMatService.insertByBo(baseMatBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、物料编码 ").append(baseMatImportVo.getMatCode()).append(" 导入成功");
            } else if (isUpdateSupport) {

                BaseMatBo baseMatBo = BeanUtil.toBean(baseMatImportVo, BaseMatBo.class);
                ValidatorUtils.validate(baseMatBo);
                baseMatBo.setMatId(baseMatVo.getMatId());
                baseMatBo.setUpdateBy(operUserId);
                baseMatService.updateByBo(baseMatBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、物料编码 ").append(baseMatImportVo.getMatCode()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、物料编码 ").append(baseMatImportVo.getMatCode()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、物料编码 " + HtmlUtil.cleanHtmlTag(baseMatImportVo.getMatCode()) + " 导入失败：";
            String message = e.getMessage();
            if (e instanceof ConstraintViolationException cvException) {
                message = StreamUtils.join(cvException.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
            }
            failureMsg.append(msg).append(message);
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<BaseMatImportVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<BaseMatImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
